#!/usr/bin/env python

import os, sys
from optparse import OptionParser

import MySQLdb as mysql
from MySQLdb.cursors import DictCursor

op = OptionParser ()
op.add_option ( "-u", "--user", dest = "user", help = "Database user", metavar = "USER", default = "root" )
op.add_option ( "-p", "--password", dest = "passwd", help = "Database password", metavar = "PASSWORD", default = "" )
op.add_option ( "-d", "--database", dest = "db", help = "Database name", metavar = "DATABASE" )
op.add_option ( "-H", "--host", dest = "host", help = "Database host", metavar = "HOST", default = "localhost" )

( options, args ) = op.parse_args ()

options = eval ( str ( options ) )
if not options [ 'db' ]:
	print "Missing 'database' parameter!"
	sys.exit ( 0 )

options [ 'cursorclass' ] = DictCursor

db = mysql.connect ( ** options )

sql = "select table_name, engine, table_collation from information_schema.tables where table_schema = '%s' and table_type = 'BASE TABLE'" % options [ 'db' ]

cur = db.cursor ()

res = db.cursor ()
res.execute ( sql )
for row in res:
	if row [ 'table_collation' ] != 'utf8_general_ci':
		sql =  "ALTER TABLE %(table_name)s CONVERT TO CHARACTER SET utf8;" % row
		print "Converting table '%(table_name)s' charset to utf8..." % row
		cur.execute ( sql )
	
	if row [ 'table_name' ] != 'page' and row [ 'engine' ] != 'InnoDB':
		sql =  "ALTER TABLE %(table_name)s ENGINE = InnoDB;" % row
		print "Converting table '%(table_name)s' engine to InnoDB..." % row
		cur.execute ( sql )

print "OK"
